<template>
    <TableView class="table">
        <template #form>
            <NSpace justify="space-between">
                <NSpace align="center">
                    资产名称:
                    <NInput style="width: 200rem" placeholder="请输入资产名称" v-model:value="paginationReactive.assetName"
                        clearable />
                    资产编号:
                    <NInput style="width: 200rem" placeholder="请输入资产编号" v-model:value="paginationReactive.assetNumber"
                        clearable />
                    资产类目:
                    <NTreeSelect style="width: 300rem" placeholder="请选择资产类目" v-model:value="paginationReactive.categoriesId"
                        clearable :options="categoryList" label-field="categoriesName" key-field="id"
                        children-field="childList" />
                    状态:
                    <NSelect style="width: 150rem" placeholder="请选择状态" v-model:value="paginationReactive.status" clearable
                        :options="[
                            { value: 0, label: '在库' },
                            { value: 1, label: '使用中' },
                            { value: 2, label: '停用' }
                        ]" />
                    <NButton type="primary" style="width: 78rem" ghost
                        @click="() => ((paginationReactive.page = 1), getDetopManagementList())">
                        查询
                    </NButton>
                </NSpace>
                <NSpace align="center">
                    <NButton type="primary" style="width: 85rem"
                        @click="$router.push({ path: '/OA/AssetsManagement/PersonalAssets/AssetsReceiveAdd' })">领用
                    </NButton>
                    <NButton type="primary" style="width: 115rem" @click="batchReturn"
                        :disabled="!dataListSelections.length">批量归还
                    </NButton>
                    <NButton type="primary" style="width: 115rem" @click="batchTransfer"
                        :disabled="!dataListSelections.length">批量转移</NButton>
                </NSpace>
            </NSpace>
        </template>

        <template #table="props">
            <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
                :loading="tableLoading" :row-key="rowKeys" :checked-row-keys="dataListSelections" striped
                @update:checked-row-keys="selectionChangeHandle" />
        </template>

        <template #pagination>
            <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
                :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
                @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
                show-size-picker show-quick-jumper :suffix="() => '页'">
                <template #prefix>
                    <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </template>
    </TableView>

    <NModal :auto-focus="false" v-model:show="modalVisibleRemark" @close="closeModal">
        <VDialogContent @close="closeModal" @submit="submitRemark" title="备注">
            <div style="width: 400rem; height: auto;">
                <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="60"
                    :model="formValue" label-align="right">
                    <NFormItem label="备注:" path="remark">
                        <NInput placeholder="请输入备注" style="min-height: 120rem;" type="textarea"
                            v-model:value="formValue.remark" clearable :allow-input="noSideSpace" />
                    </NFormItem>

                    <NFormItem label="附件:">
                        <Upload :max="1" v-model:fileList="formValue.file" accept="image/*" listType="image-card" />
                    </NFormItem>
                </NForm>
            </div>
        </VDialogContent>
    </NModal>
</template>
<script setup lang="ts">
import {
    NSpace, NButton, NDataTable, NPagination, useMessage, NModal, NInput, NSelect,
    NForm, NFormItem, NTreeSelect, NImage
} from 'naive-ui'
import { h, reactive, ref, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import Upload from '@/components/Upload/upload.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useViewerStore } from '@/views/OA/Common/store'
import router from '@/router'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisibleRemark = ref(false)

const rowKeys: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
    {
        width: 30,
        type: 'selection'
    },
    {
        title: '资产编号',
        key: 'assetNumber',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '资产名称',
        key: 'assetName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '资产类目',
        key: 'categoriesName',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '状态',
        key: 'statusValue',
        width: 60,
        align: useStore.isCenter
    },
    {
        title: '附件缩略图',
        key: 'picPath',
        width: 60,
        align: useStore.isCenter,
        render: (row: any) => [
            row.picPath ? h(NImage, { src: row.picPath, width: 100, height: 80, objectFit: 'contain' }) : null
        ]
    },
    {
        title: '备注',
        key: 'userRemark',
        width: 140,
        align: useStore.isCenter
    },
    {
        title: '操作',
        key: 'action',
        align: useStore.isCenter,
        width: 100,
        fixed: 'right',
        render: (row: any) => [
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: () => {
                        useStore.assetsReturnList = [row]
                        router.push({ path: '/OA/AssetsManagement/PersonalAssets/AssetsReturnAdd' })
                    }
                },
                {
                    default: () => '归还'
                }
            ),
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: () => {
                        useStore.assetsTransferList = [row]
                        router.push({ path: '/OA/AssetsManagement/PersonalAssets/AssetsTransferAdd' })
                    }
                },
                {
                    default: () => '转移'
                }
            ),
            h(
                NButton,
                {
                    type: 'primary',
                    quaternary: true,
                    onClick: async () => {
                        assetsId.value = row.id
                        formValue.remark = row.userRemark
                        if(row.picPath && row.picPath !== '') {
                            formValue.file = [{ url: row.picPath, status: 'finished' }]
                        }
                        modalVisibleRemark.value = true
                    }
                },
                {
                    default: () => '备注'
                }
            )
        ]
    }
]
const closeModal = () => {
    modalVisibleRemark.value = false
    initFormValue()
}
const initFormValue = () => {
    formValue.file = []
    formValue.remark = null
}
// 备注表单数据
const formValue = reactive<Record<string, any>>({
    remark: null, //事由
    file: [] //附件
})
// 备注表单数据效验
const rules = {
    remark: {
        required: false,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (value?.length > 100) return new Error('事由字数不得超过100')
            return true
        }
    }
}
// 上一页下一页
const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    assetName: null, //资产名称
    assetNumber: null, //资产编号
    categoriesId: null, //资产类目
    status: null, //状态
    onChange: (page: number) => {
        paginationReactive.page = page
        getDetopManagementList()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        getDetopManagementList()
    }
})
// table的key选择
const dataListSelections: any = ref([])
const selectionChangeHandle = (_: any) => dataListSelections.value = _
// 批量归还
const batchReturn = () => {
    if (!dataListSelections.value.length) return message.warning('请先选择需要归还的资产')
    useStore.assetsReturnList = tableData.value.filter((it: any) => dataListSelections.value.includes(it.id))
    router.push({ path: '/OA/AssetsManagement/PersonalAssets/AssetsReturnAdd' })
}
// 批量转移
const batchTransfer = () => {
    if (!dataListSelections.value.length) return message.warning('请先选择需要转移的资产')
    useStore.assetsTransferList = tableData.value.filter((it: any) => dataListSelections.value.includes(it.id))
    router.push({ path: '/OA/AssetsManagement/PersonalAssets/AssetsTransferAdd' })
}
// 备注提交
const assetsId = ref()
const submitRemark = async () => {
    modalVisibleRemark.value = false
    tableLoading.value = true
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'updateUserRemark',
        override: {
            data: {
                id: assetsId.value,
                userRemark: formValue.remark,
                picPath: (formValue.file.length > 0) ? formValue.file[0].url : null
            }
        }
    })
    if (error) {
        initFormValue()
        tableLoading.value = false
        return message.error('提交失败')
    }
    if (res.code !== 0) {
        initFormValue()
        tableLoading.value = false
        return message.error('提交失败')
    }
    message.success('提交成功')
    tableLoading.value = false
    initFormValue()
    getDetopManagementList()
}
// 获取类目下拉
const categoryList = ref<any>([])
const getCategoryList = async () => {
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getCategoryList'
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    categoryList.value = res.data
}
// 获取列表
const tableData: any = ref([])
const tableLoading = ref(false)
const getDetopManagementList = async () => {
    tableLoading.value = true
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'getUserAssetsList',
        override: {
            params: {
                page: paginationReactive.page,
                limit: paginationReactive.pageSize,
                assetNumber: paginationReactive.assetNumber,
                assetName: paginationReactive.assetName,
                categoriesId: paginationReactive.categoriesId,
                status: paginationReactive.status
            }
        }
    })
    tableLoading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    tableData.value = []
    setTimeout(() => {
        tableData.value = res.data.list
        paginationReactive.itemCount = res.data.totalCount
    }, 0)
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')

const keyUpDown = (e: any) => e.key == 'Enter' && getDetopManagementList()
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
    () => route,
    async () => {
        if (route.path == '/OA/AssetsManegement/PersonalAssets/PersonalAssets') {
            getCategoryList()
            getDetopManagementList()
            window.addEventListener('keyup', keyUpDown, false)  // 回车
        }
    },
    { deep: true, immediate: true }
)

</script>
<style scoped lang="scss">
.table {
    padding: 29rem 30rem 42rem;
}
</style>